package com.cennavi.minemapdemo.activity.basic;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.util.Config;
import com.cennavi.minemapdemo.util.DensityUtil;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.MarkerLayerOptions;

import java.util.UUID;

/**
 * 基础地图授权
 */
public class AuthorizationMapActivity extends BaseActivty {

    //地图视图
    private MapView mapView;
    //地图操作类
    private MineMap mineMap;
    private Context mContext;
    private TextView textView;
    private MarkerLayerOptions.MarkerItem marker; // 定位的标记点

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);
        setContentView(R.layout.activity_map_authoriztion);
        mapView = findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
        textView = findViewById(R.id.textView);
        //初始化地图
        initMap();
    }
    public void onGetKey(View view){

        String androidID = new GetLocalKey().comparisonKey(mContext);
        textView.setText(androidID);
    }

    //生命周期
    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null)
            mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mapView != null)
            mapView.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //2.0.6及之后版本 需要将加入地图的图片资源进行清理
        if (mineMap != null)
            mineMap.removeImagesAll();

        if (mapView != null)
            mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (mapView != null){
            mapView.onLowMemory();
        }
    }

    public void zoomIn(View view) {
        if (mineMap != null) {
            mineMap.moveCamera(CameraUpdateFactory.zoomIn());
        }
        mineMap.addOnMapClickListener(new MineMap.OnMapClickListener() {
            @Override
            public void onMapClick(@NonNull LatLng latLng) {
                Log.i("ljr","hello");
            }
        });

    }

    public void zoomOut(View view) {
        if (mineMap != null) {
            mineMap.moveCamera(CameraUpdateFactory.zoomOut());
        }
    }

    private void initMap() {
        //mine map sdk 2.0.6之前生效
//        mapView.setStyleUrl(Config.mBaseUrl + Config.MAP_ID);
        //授权码写入
//        mapView.setAuthorizeURL("https://minedata.cn/lbsservice/mapauthorize/authority/getAuthority");
//        mapView.setAuthorizeKey("ba47dd397e4e84a641ea6291cd5d2f582cc4566f");
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(MineMap oMineMap) {
                mineMap = oMineMap;
                mineMap.setDebugActive(false);
                mineMap.getUiSettings().setZoomControlsEnabled(false);
                mineMap.getUiSettings().setRotateGesturesEnabled(true);// 是否可以旋转地图
                mineMap.getUiSettings().setTiltGesturesEnabled(true);
                mineMap.setStyleUrl(Config.mBaseUrl + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {
                    @Override
                    public void onStyleLoaded(String s) {

                        //mine map sdk 2.0.6及之后版本这样使用
                        addImageToMap();
                        mineMap.setTrafficShow(true);//显示路况

                    }
                });
                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.getUiSettings().setCompassGravity(Gravity.LEFT);
//                mineMap.getUiSettings().setCompassImage(getResources().getDrawable(R.mipmap.icon_compass));
                mineMap.getUiSettings().setCompassMargins(DensityUtil.dip2px(mContext, 11), DensityUtil.dip2px(mContext, 80),
                        0, 0);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(32.01627, 118.87309)).zoom(14)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mineMap.setMinZoomPreference(3);//设置最低的展示级别

                marker = new MarkerLayerOptions.MarkerItem().icon(R.drawable.ic_arrow+"").position(new LatLng(32.01627, 118.87309));
                MarkerLayerOptions Layer = new MarkerLayerOptions("locationMarkerLayer")
                        .iconAnchor(MarkerLayerOptions.ANCHOR_CENTER)//基准点
                        .iconPitchAlignment(MarkerLayerOptions.PITCH_ALIGNMENT_MAP);
                Layer.add(marker);
            }
        }
        ,new MapView.OnErrorCallback() {
            //授权结果
            @Override
            public void callback(String s, int i) {
                Snackbar.make(mapView, s +":"+i, Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();            }
        }
        );
    }
    //加载可能的图片资源
    private void addImageToMap() {

        Bitmap icon = drawableToBitmap(this, R.drawable.ic_arrow);
        mineMap.addImage(R.drawable.ic_arrow + "", icon);

    }

    public static Bitmap drawableToBitmap(Context context, int vectorDrawableId) {
        Bitmap bitmap = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            Drawable vectorDrawable = context.getDrawable(vectorDrawableId);
            if (vectorDrawable != null) {
                bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
                        vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_4444);
                Canvas canvas = new Canvas(bitmap);
                vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                vectorDrawable.draw(canvas);
            }
        } else {
            bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId);
        }
        return bitmap;
    }


    /**
     * 本地key授权验证
     */
    private class GetLocalKey {

        private String comparisonKey(Context context) {
            String device_id = null;
            try {
                //没有网络 找Share
                device_id = "";
//                device_id = getString(context, "MineMap_device_id", "");
                if (TextUtils.isEmpty(device_id)) {
                    device_id = getPhoneID(context);
                    putString(context, "MineMap_device_id", device_id);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return device_id;
        }

        //获取手机的唯一标识Map
        private String getPhoneID(Context context) {
            StringBuffer stringBuffer = new StringBuffer();
            try {
                //androidID
                String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
                if (!TextUtils.isEmpty(androidID)) {
                    stringBuffer.append(androidID);
                }
                //序列号（sn）
                @SuppressLint("MissingPermission") String sn = Build.SERIAL;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {

                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return sn;
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        sn = Build.getSerial();
                    }
                }
                if (!TextUtils.isEmpty(sn)&&!sn.equals("unknown")) {
                    stringBuffer.append(sn);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuffer.toString();
        }

        /**
         * 得到全局唯一UUID
         */
        private String uuid;

        private String getUUID(Context mContext) {
            SharedPreferences mShare = mContext.getSharedPreferences("uuid", mContext.MODE_PRIVATE);
            if (mShare != null) {
                uuid = mShare.getString("uuid", "");
            }
            if (TextUtils.isEmpty(uuid)) {
                uuid = UUID.randomUUID().toString();
                mShare.edit().putString("uuid", uuid).commit();
            }
            return uuid;
        }

        private SharedPreferences mSharedPreferences;

        /**
         * @param context
         * @param key
         * @param values
         */
        private void putString(Context context, String key, String values) {
            if (mSharedPreferences == null) {
                mSharedPreferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
            }
            mSharedPreferences.edit()
                    .putString(key, values)
                    .apply();
        }


        /**
         * @param context
         * @param key
         * @param defaultValues
         * @return
         */
        private String getString(Context context, String key, String defaultValues) {
            if (mSharedPreferences == null) {
                mSharedPreferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
            }
            return mSharedPreferences.getString(key, defaultValues);
        }
    }

}
